package main

import (
	"errors"
	"github.com/labstack/echo/v4"
	"math/rand"
	"net/http"
)

var (
	UnauthorizedError = errors.New("unauthorized error")
	ParamError        = errors.New("param error")
)

func main() {

	e := echo.New()
	e.Use(HandleError)

	e.GET("/error", RandomError)

	e.Start(":80")

}

func RandomError(c echo.Context) error {
	num := rand.Intn(3)
	switch num {
	case 0:
		return c.JSON(http.StatusOK, "success")
	case 1:
		return ParamError
	case 2:
		return UnauthorizedError
	default:
		return c.JSON(http.StatusOK, "success")
	}
}

func HandleError(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		//todo ... pre

		err := next(c)
		if err != nil {
			if errors.Is(err, UnauthorizedError) {
				return echo.NewHTTPError(http.StatusUnauthorized)
			} else if errors.Is(err, ParamError) {
				return echo.NewHTTPError(http.StatusBadRequest)
			} else {
				return echo.NewHTTPError(http.StatusInternalServerError)
			}
		}

		//todo..  post
		return nil

	}

}
